package servlet;

import dao.UserinfoDao;
import entity.Userinfo;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 根据id查询用户信息
 */
@WebServlet("/GetUserInfoServlet")
public class GetUserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求参数
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");

        //2. 根据用户id查询用户对象
        JSONObject resData = new JSONObject();
        resData.put("code", 200);
        UserinfoDao userinfoDao = new UserinfoDao();
        try {
            Userinfo user = userinfoDao.getUserById(id);
            resData.put("data", user);
        } catch (Exception e) {
            resData.put("data", null);
        }

        //3.响应数据给前端调用者：
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(resData);
        writer.flush();
        writer.close();

    }
}
